package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"xabin.com/ginesstential/common"
	"xabin.com/ginesstential/model"
)

// AuthMiddleware 认证组件
func AuthMiddleware() gin.HandlerFunc {

	return func(ctx *gin.Context) {
		// Authorization header
		tokenString := ctx.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "权限不足",
			})
			ctx.Abort()
			return
		}

		tokenString = tokenString[7:]

		token, claims, err := common.ParserToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "权限不足",
			})
			ctx.Abort()
			return
		}

		userID := claims.UserID
		db := common.GetDB()
		var user model.User
		db.First(&user, userID)

		if user.ID == 0 {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "权限不足",
			})
			ctx.Abort()
			return
		}

		ctx.Set("user", user)
		ctx.Next()
	}
}
